(in-package "MUDRA")


(defun dojo-attrs (attrs)
  (loop for (key value) on attrs by #'cddr
	nconc (list 
	       (intern (js::symbol-to-js key) (symbol-package :foo))
	       value)))

(defun check-dojo-tag-packaging (tag)
  (let ((p (symbol-package tag)))
    (multiple-value-bind (sym status) (find-symbol (symbol-name tag) p)
      (unless (eq sym tag)
	(warn "~S not found in package MUDRA" tag))
      (unless (eq :external status)
	(warn "~S is not external" tag))
      (unless (eq p (find-package "MUDRA"))
	(warn "~S isn't in package MUDRA" tag)))))

(defmacro def-dojo-attribute (name ())
  `(progn 
    (pushnew (list ',name) *known-dojo-attributes*)
    ',name))

(defvar *known-dojo-attributes* nil)



(defun sweep-dojo-attributes (attributes)
  (loop for (name value) on attributes by #'cddr
	as info? = (assoc name *known-dojo-attributes*)
	unless info?
	do (warn "Unknown dojo attribute ~S" name)
	nconc (list name value)))

(defun make-dojo-header (type-name attributes more-attributes)
  (setf attributes (sweep-dojo-attributes attributes))
  (setf more-attributes (sweep-dojo-attributes more-attributes))
  `(div :dojo-type ,type-name ,@attributes ,@more-attributes))

(defmacro def-dojo-tag (name (&rest required-attrs)
			     &optional 
			     &key extra-attributes)
  (check-dojo-tag-packaging name)
  (let ((dojo-type (js::symbol-to-js
		    (intern 
		     (subseq (symbol-name name) 4)
		     (symbol-package :keyword)))))
    `(defhtmltag ,name (attrs body)
      ,@(loop for attr in required-attrs
	      collect `(assert (getf attrs ,attr)))
      (let ((head (make-dojo-header ,dojo-type attrs ',extra-attributes)))
      (list* head body)))))
